<template>
  <el-dialog
    title="生产计划单"
    :visible="selectImportMaterialDialog"
    width="70%"
    class="mo-order-select"
    @close="selectImportMaterialClose"
  >
    <div class="app-container">
      <div class="layout-box">
        <el-form :inline="true" label-width="70px" class="search-top">
          <div class="search-sub">
            <el-form-item label-width="82">
              <el-input
                v-model="searchForm.ppNumber"
                clearable
                size="small"
                placeholder="销售单号"
                style="width: 150px"
              />
            </el-form-item>

            <el-form-item label-width="82">
              <el-date-picker
                v-model="valueDate"
                type="daterange"
                align="right"
                unlink-panels
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                style="width: 250px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
                >搜索
              </el-button>
            </el-form-item>
          </div>
          <div>
            <el-button
              type="primary"
              plain
              icon="el-icon-menu"
              size="mini"
              @click="checkleAll"
              >查询所有</el-button
            >
          </div>
        </el-form>
        <!-- 单据列表 -->
        <el-table
          :data="billTableData"
          style="width: 100%"
          v-loading="loading"
          :height="maxHeight"
          ref="billTable"
          :expand-row-keys="expands"
          @expand-change="handleExpand"
          row-key="mp_code"
          @select="handleParentChange"
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-table
                :data="scope.row.list"
                style="width: 100%"
                :ref="'detailTable' + scope.row.mp_code"
                @select="handleChildChange"
                border
                class="child-table"
              >
                <el-table-column
                  prop="inv_code"
                  label="物料编码"
                  align="center"
                >
                </el-table-column>
                <el-table-column label="物料名称" align="center">
                  <template v-slot="scope">
                    <div>
                      <span
                        >{{ scope.row.inv_name }} {{ scope.row.inv_attribute }}</span
                      >
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="unit_name"
                  label="主计量"
                  align="center"
                  width="100"
                >
                </el-table-column>
                <el-table-column
                  prop="surplus"
                  label="数量"
                  align="center"
                  width="150"
                >
                  <template v-slot="scope">
                    <div style="text-align: right">
                      <span>{{ scope.row.surplus }} </span>
                    </div>
                  </template>
                </el-table-column>
           <el-table-column label="用料方式" align="center">
                  <template v-slot="scope">
                    <span>{{ scope.row.inv_in_type | matchingInvType }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="piece"
                  label="包装件数"
                  align="center"
                  width="100"
                >
                </el-table-column>
         
                <el-table-column prop="remarks" label="备注" align="center">
                </el-table-column>
                <el-table-column type="selection" width="50" align="center">
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column
            prop="pp_number"
            label="销售单号"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column prop="mp_code" label="计划单号" align="center">
          </el-table-column>
          <el-table-column prop="pp_date" label="订单交期" align="center">
                <template v-slot="scope">
              <span>
                {{ scope.row.pp_date | inMaterTime }}
              </span>
            </template>
          </el-table-column>
      
          <el-table-column prop="work_type" label="业务类型" align="center">
          </el-table-column>
          <el-table-column prop="invoice_date" label="单据日期" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.invoice_date | inMaterTime }}</span>
            </template>
          </el-table-column>

          <el-table-column type="selection" width="50" align="center">
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <pagination
        v-if="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getBillList"
      />
    </div>
    <div class="ImportMaterial-success">
      <div>
        <el-button
          :disabled="successStatus"
          type="primary"
          @click="handleSuccess"
          >确定</el-button
        >
        <el-button @click="handleClose">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { listImportBill, listImportDetail } from "../../api/order";
let self;
export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      detailLoding: true,
      //查询单据参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        ppNumber: "",
        startDate: "",
        endDate: "",
      },
      // 小数位数
      decimal: 2,
      // 总条数
      total: 0,
      // 最大高度
      maxHeight: null,
      //单据数据
      billTableData: [],
      //已选单据
      billSelected: [],
      //已选物料
      materialSelected: [],
      expands: [],
      successStatus: true,
      searchForm: {
        ppNumber: "",
      },
      //查询明细参数
      queryDetail: {
        mpCode: "",
        customer: "",
        invCode: "",
        invName: "",
        startDate: "",
        endDate: "",
      },
      // 开始时间/结束时间配置
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      valueDate: [],
    };
  },
  props: {
    selectImportMaterialDialog: {
      type: Boolean,
      default: true,
    },
    supplyType: {
      type: String,
      default: "0",
    },
    warehouse: {
      type: String,
      default: "",
    },
    optionsInvInType:{
      type:Array,
      default:()=>{
        return []
      }
    }
  },
    beforeCreate() {
    self = this;
  },
  created() {
    this.getBillList();
  },
  methods: {
    //查询所有
    checkleAll() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 100,
        ppNumber: "",
        startDate: "",
        endDate: "",
      };
      this.searchForm.ppNumber = "";
      this.valueDate = [];
      this.getBillList();
    },

    // 获取单据
    getBillList() {
      this.loading = true;
      listImportBill(this.queryParams).then((res) => {
        if (res.code == 200) {
          this.expands = [];
          this.loading = false;
          res.rows.forEach((item) => {
            item.list = [];
          });
          this.billTableData = res.rows;
          this.total = res.total;
          this.maxHeight = `${document.documentElement.clientHeight}` - 390;
        }
      });
    },

    // 搜索
    handleSearch() {
      this.queryParams.ppNumber = this.searchForm.ppNumber;
      if (this.searchForm.ppNumber == "" && this.valueDate.length == 0) {
        this.msgError("请输入搜索条件");
      } else {
        // 日期转换
        if (this.valueDate.length > 0) {
          this.queryParams.startDate = this.parseTime(this.valueDate[0]);
          this.queryParams.endDate = this.setTime(this.valueDate[1]);
        } else {
          this.queryParams.startDate = "";
          this.queryParams.endDate = "";
        }
        this.getBillList();
      }
    },

    //展开获取物料信息
    handleExpand(row, expandRow) {
      let loIndex = this.expands.indexOf(row.mp_code);
      if (loIndex < 0) {
        this.expands.push(row.mp_code);
      } else {
        this.expands.splice(loIndex, 1);
      }

      if (row.list.length == 0) {
        this.queryDetail.mpCode = row.mp_code;
        listImportDetail(this.queryDetail).then((res) => {
          if (res.code == 200) {
            row.list = [];
            row.list = [...res.rows];
            this.getDecimal();
          }
        });
      } else {
        setTimeout(() => {
          if (this.billSelected.length > 0) {
            let code = this.billSelected[0].mp_code;
            if (
              this.billSelected.length > 0 &&
              this.materialSelected.length > 0 &&
              this.$refs["detailTable" + code] !== undefined
            ) {
              this.materialSelected.forEach((item) => {
                this.$refs["detailTable" + code].toggleRowSelection(item, true);
              });
            }
          }
        }, 0);
      }
    },

    //批量选择单据
    handleParentChange(row) {
      let del_row;
      this.billSelected = [];
      if (row.length > 1) {
        del_row = row.shift(); //得到已删除的单据
        this.$nextTick(() => {
          this.$refs.billTable.toggleRowSelection(del_row, false);
        });
        // 清除已选中
        if (
          del_row.list.length > 0 &&
          this.$refs["detailTable" + del_row.mp_code] !== undefined
        ) {
          del_row.list.forEach((row) => {
            setTimeout(() => {
              this.$refs["detailTable" + del_row.mp_code].toggleRowSelection(
                row,
                false
              );
            }, 0);
          });
        }
      }
      this.billSelected = row; //核心->赋值单据
      if (row.length > 0) {
        if (row[0].list.length == 0) {
          //无物料数据，发送请求
          this.queryDetail.mpCode = row[0].mp_code;
          listImportDetail(this.queryDetail).then((res) => {
            if (res.code == 200) {
              row[0].list = [...res.rows];
              this.getDecimal();
              //展开当前
              if (this.expands.indexOf(row[0].mp_code) < 0) {
                this.expands.push(row[0].mp_code);
              }
              this.materialSelected = row[0].list; //核心->赋值物料
              this.successStatus = false;
              this.handleCommon(row[0].mp_code, row[0].list, true);
            }
          });
        } else {
          //展开当前
          if (this.expands.indexOf(row[0].mp_code) < 0) {
            this.expands.push(row[0].mp_code);
          }
          this.materialSelected = row[0].list; //核心->赋值物料
          this.successStatus = false;
          this.handleCommon(row[0].mp_code, row[0].list, true);
        }
      } else {
        if (
          this.materialSelected.length > 0 &&
          this.$refs["detailTable" + this.materialSelected[0].mp_code] !==
            undefined
        ) {
          this.handleCommon(
            this.materialSelected[0].mp_code,
            this.materialSelected,
            false
          );
        }
        this.materialSelected = [];
        this.successStatus = true;
      }
    },

    //批量选择物料
    handleChildChange(row) {
      if (row.length > 0 && this.billSelected.length == 0) {
        this.billTableData.forEach((item) => {
          if (item.mp_code == row[0].mp_code) {
            this.billSelected[0] = item;
            this.$refs.billTable.toggleRowSelection(item, true);
          }
        });
      }

      //当没有选择单据，选择子物料信息时
      if (row.length > 0 && row[0].mp_code !== this.billSelected[0].mp_code) {
        this.$refs.billTable.toggleRowSelection(this.billSelected[0], false);
        let code = this.billSelected[0].mp_code;
        if (this.$refs["detailTable" + code] !== undefined) {
          this.materialSelected.forEach((row) => {
            this.$refs["detailTable" + code].toggleRowSelection(row, false);
          });
        }

        this.billTableData.forEach((item) => {
          if (item.mp_code == row[0].mp_code) {
            this.billSelected[0] = item;
            this.$refs.billTable.toggleRowSelection(item, true);
          }
        });
      } else if (row.length == 0) {
        this.$refs.billTable.toggleRowSelection(this.billSelected[0], false);
      } else if (
        row.length > 0 &&
        row[0].mp_code == this.billSelected[0].mp_code
      ) {
        this.$refs.billTable.toggleRowSelection(this.billSelected[0], true);
      }
      this.materialSelected = row;
      if (this.materialSelected.length > 0) {
        this.successStatus = false;
      } else {
        this.successStatus = true;
      }
    },

    //公用选择方法
    handleCommon(code, list, type) {
      this.$nextTick(() => {
        list.forEach((row) => {
          this.$refs["detailTable" + code].toggleRowSelection(row, type);
        });
      });
    },

    //格式化数量单价金额小数位数
    getDecimal() {
      if (this.billTableData.length > 0) {
        this.billTableData.forEach((obj) => {
          if (obj.list.length > 0) {
            obj.list.forEach((item) => {
              if (item.price !== null && item.price !== undefined) {
                item.price = parseFloat(item.price).toFixed(this.decimal);
              }
              if (item.surplus !== null && item.surplus !== undefined) {
                item.surplus = parseFloat(item.surplus).toFixed(this.decimal);
              }
              if (item.amount !== null && item.amount !== undefined) {
                item.amount = parseFloat(item.amount).toFixed(2);
              }
              if (item.quantity !== null && item.quantity !== undefined) {
                item.quantity = parseFloat(item.quantity).toFixed(this.decimal);
              }
            });
          }
        });
      }
    },

    // 弹框状态
    selectImportMaterialClose() {
      this.$emit("selectImportMaterialClose");
    },

    //确定选取
    handleSuccess() {
      // console.log( this.billSelected)
      //  console.log( this.materialSelected)
      this.$emit(
        "handleImportMaterialSuccess",
        this.billSelected,
        this.materialSelected
      );
      this.selectImportMaterialClose();
    },

    // 关闭弹框
    handleClose() {
      this.selectImportMaterialClose();
    },
    //时间+23时59分59秒
    setTime(date) {
      date.setHours(date.getHours() + 23);
      date.setMinutes(date.getMinutes() + 59);
      date.setSeconds(date.getSeconds() + 59);
      let time = new Date(date);
      return (
        time.getFullYear() +
        "-" +
        (time.getMonth() + 1) +
        "-" +
        time.getDate() +
        " " +
        time.getHours() +
        ":" +
        time.getMinutes() +
        ":" +
        time.getSeconds()
      );
    },
  },
  filters: {
    //时间格式化
    inMaterTime(date) {
      let time = new Date(date);
      return (
        time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate()
      );
    },

    //交期状态
    filterStatus(status) {
      switch (status) {
        case "0":
          return "预计";
          break;
        case "1":
          return "确认";
          break;
        default:
          return "";
      }
    },

    //匹配用料方式
    matchingInvType(data) {
      let supply = "";
      if (self.optionsInvInType && self.optionsInvInType.length > 0) {
        self.optionsInvInType.forEach((item) => {
          if (item.dictValue == data) {
            supply = item.dictLabel;
          }
        });
      }
      return supply;
    },

  },
};
</script>
<style lang="scss">
.mo-order-select {
  .el-dialog__body {
    height: calc(100vh - 250px);
    position: relative;
  }
  .el-range-editor--medium.el-input__inner {
    line-height: 32px;
  }
  .el-range-editor--medium .el-range__icon,
  .el-range-editor--medium .el-range__close-icon,
  .el-range-editor--medium .el-range-separator {
    line-height: 24px;
  }
  .el-range-editor--medium.el-input__inner {
    height: 32px;
  }
  .el-table--border {
    border-top: none;
  }
  .parent-table {
    th,
    td {
      border-right: 1px solid #dfe6ec;
    }
    th:nth-of-type(1),
    td:nth-of-type(1) {
      border-left: 1px solid #dfe6ec;
    }
  }
  .child-table {
    margin-bottom: 24.5px;
    margin-top: -5.5px;
    box-sizing: border-box;
  }
  .search-top {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .el-pagination {
    left: 0;
  }

  .el-table__header-wrapper {
    .el-checkbox {
      display: none;
    }
  }
  .app-container {
    padding-top: 0;
  }

  .layout-box {
    .el-link.is-underline:hover:after {
      border: none;
    }

    .search-box {
      display: flex;
      margin-bottom: 20px;

      .search-input {
        display: flex;
        margin-right: 15px;

        .input-data {
          min-width: 220px !important;
        }

        .el-input {
          margin-right: 15px;
        }
      }
    }

    .sort-active {
      background: #1890ff !important;
      border-color: #1890ff !important;
      color: #ffffff !important;
    }

    .con-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .material-sort {
      span {
        font-size: 14px;
        padding: 0px 15px;
        background: #f4f4f5;
        color: #999;
        display: inline-block;
        border-radius: 3px;
        margin-left: 5px;
        margin-right: 5px;
        cursor: pointer;
        line-height: 26px;
        border: 1px solid #e9e9eb;
      }
    }
  }

  .ImportMaterial-success {
    position: absolute;
    bottom: 20px;
    right: 40px;

    button {
      padding: 8px 40px;
    }
  }
}
</style>
